package reflect;

import java.io.File;
import java.lang.reflect.Method;

public class Test5 {
    public static void main(String[] args) throws Exception {
        File dir = new File(
                Test4.class.getResource(".").toURI()
        );
        //获取该目录中所有的.class文件
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File sub : subs) {
            String fileName = sub.getName();
            //根据.class文件名获取类名  例如:Person.class
            String className = fileName.substring(0, fileName.indexOf("."));
            //加载类对象
            Class cls = Class.forName(
                    Test4.class.getPackage().getName() + "." + className
            );
            if (cls.isAnnotationPresent(AutoRunClass.class)) {
                System.out.println("正在实例化:" + cls.getName());
                Object obj = cls.newInstance();
                System.out.println(obj);

                //获取所有方法
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)) {
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int num = arm.value();
                        System.out.println("自动调用:"+method.getName()+"()"+num+"次");
                        for (int a=0;a<num;a++){
                            method.invoke(obj);
                        }
                    }
                }
            }
        }
    }
}